﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PSE.Framework.ProviderLoader.Configuration;

namespace PSE.Framework.ProviderLoader
{
    public class ProviderLoader<T>
    {
        /// <summary>
        /// Verificar se um provider existe em um coleção de providers
        /// </summary>
        /// <param name="providerInfoCollection"></param>
        /// <param name="providerName"></param>
        public static bool ProviderExists(ProviderConfigurationElementCollection providerInfoCollection, string providerName)
        {
            if (providerInfoCollection == null)
                throw new ArgumentNullException("providerInfoCollection");

            if (string.IsNullOrEmpty(providerName))
                throw new ArgumentNullException("providerName");

            return providerInfoCollection[providerName] != null;
        }

        /// <summary>
        /// Carregar um provider
        /// </summary>
        /// <param name="providerInfo"></param>
        /// <returns></returns>
        public static T LoadProvider(ProviderConfigurationElementCollection providerInfoCollection, string providerName)
        {
            if (ProviderExists(providerInfoCollection, providerName))
                return LoadProvider(providerInfoCollection[providerName]);
            else
                throw new Exception(string.Format("The provider '{0}' don't exists in the provider collection.", providerName));
        }


        /// <summary>
        /// Carregar um provider
        /// </summary>
        /// <param name="providerInfo"></param>
        /// <returns></returns>
        public static T LoadProvider(ProviderConfigurationElement providerInfo)
        {
            if (providerInfo == null)
                throw new ArgumentNullException("providerInfo");

            if (providerInfo.Type == null)
                throw new ArgumentNullException("providerInfo.Type");

            if (!providerInfo.Type.IsSubclassOf(typeof(BaseProvider)))
                throw new Exception("Invalid provider type. The provider must inherit from BaseProvider.");

            return (T)Activator.CreateInstance(providerInfo.Type, providerInfo);
        }
    }
}
